/**
 * 下午7:04:09
 */
package com.hsnn.medstgmini.pro.project.controller;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.pro.project.model.BidPubSettings;
import com.hsnn.medstgmini.pro.project.model.BidPubSettingsLog;
import com.hsnn.medstgmini.pro.project.model.form.ProdProjectForm;
import com.hsnn.medstgmini.pro.project.service.BidPubSettingsManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.BeanCopierUtils;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.PdfUtil;

/**
 * @author hsnn
 *
 */
@Controller
@RequestMapping("/bidPubSettings")
public class BidPubSettingsController {
	 private static final Logger log = Logger.getLogger(BidPubSettingsController.class);
	 	@Value("#{sysProp['system.pub.filepath']}")
	    private  String filepath;
	 	
		@Autowired
		private BidPubSettingsManager bidPubSettingsManager;

		@Autowired
		private HttpServletRequest request;
		
		@Autowired
		private HttpSession session;
		
		/**
		 *@category 去项目列表
		 *@author 应晓川
		 *@date 2015年8月27日09:58:56
		 *@return
		 */
		@RequestMapping("/toList")
		public String toList(){
			return "/pro/project/bidPubSettings/projList";
		}
		
		/**
		 *@category 去项目公示详情
		 *@author 应晓川
		 *@date 2015年9月1日19:16:42
		 *@return
		 */
		@RequestMapping("/toDetailList")
		public String toDetailList(String projId){
			request.setAttribute("projId", projId);
			return "/pro/project/bidPubSettings/detailList";
		}
		
		/**
		 * @category 获取项目公示详情表格
		 * @author 应晓川
		 * @date 2015年9月1日19:19:20
		 * @return
		 */
		@RequestMapping("/getDetailList")
		@ResponseBody
		public Pagination getDetailList(String projId) {
			Pagination page = new Pagination(request);
			try {
				page.getConditions().put("projId", projId);
				page = bidPubSettingsManager.getBidPubSettingsList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
				page.setSuccess(false);
			}
			return page;
		}
		
		/**
		 * @category 去sql执行结果预览
		 * @date 2015年9月2日11:22:32
		 * @author yxc
		 * @return
		 */
		@RequestMapping("/toExecScriptFile")
		public String toExecScriptFile() {
			return "/pro/project/bidPubSettings/previewSql";
		}
		
		/**
		 * @category 执行sql获取结果集
		 * @author 应晓川
		 * @date 2015年9月2日11:28:02
		 * @return
		 */
		@RequestMapping("/getExecScriptFile")
		@ResponseBody
		public Pagination getExecScriptFile(String sql) {
			Pagination page = new Pagination(request);
			try {
				String sqlFormat =new String(sql.getBytes("ISO-8859-1"),"UTF-8"); 
				page.getConditions().put("sql", sqlFormat);
				page = bidPubSettingsManager.getExecScriptFile(page);
				if(page.getRows()!=null && page.getForm()!=null){
					page.setSuccess(true);
				}
			} catch (Exception e) {
				log.error("",e);
				page.setMsg("SQL执行失败！请重新输入");
				page.setSuccess(false);
			}
			return page;
		}
		
		/**
		 * @category 新增sql语句
		 * @author 应晓川
		 * @date 2015年9月6日09:02:27
		 * @return
		 */
		@RequestMapping("/addExecScriptFile")
		@ResponseBody
		public Pagination addExecScriptFile(BidPubSettings bidPubSettings) {
			Pagination page = new Pagination(request);
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			String sql = bidPubSettings.getScriptFile();
			try {
				String[] fliter = {"delete","updata","drop","show","alter","insert"};
				for (String str:fliter) {
					if(sql.toLowerCase().contains(str)){
						page.setMsg("SQL脚本包含禁用字符:"+str);
						page.setSuccess(false);
						return page;
					}
				}
				page.getConditions().put("sql", sql);
				page = bidPubSettingsManager.getExecScriptFile(page);
				if(page.getRows()!=null && page.getForm()!=null){
					bidPubSettings.setBidPubSettingsId(UUID.randomUUID().toString());
					bidPubSettings.setScriptSubmitUser(user.getId());
					Timestamp now =  DateUtil.getTimeStamp();
					bidPubSettings.setScriptSubmitDatetime(now);
					bidPubSettings.setStatus(Constants.OP_TYPE_ADD);//状态0新建1已执行
					bidPubSettings.setUpdDatetime(now);
					bidPubSettings.setUpdUser(user.getId());
					if(bidPubSettingsManager.save(bidPubSettings)){
						BidPubSettingsLog bidPubSettingsLog = new BidPubSettingsLog();
						BeanCopierUtils.copyProperties(bidPubSettings, bidPubSettingsLog);
						bidPubSettingsLog.setLogId(UUID.randomUUID().toString());
						bidPubSettingsManager.save(bidPubSettingsLog);
						page.setSuccess(true);
					}
				}
			} catch (Exception e) {
				log.error("",e);
				page.setMsg("SQL执行失败！请重新输入");
				page.setSuccess(false);
			}
			return page;
		}		
		/**
		 * @category 修改sql语句
		 * @author 应晓川
		 * @date 2015年9月6日09:18:10
		 * @return
		 */
		@RequestMapping("/editExecScriptFile")
		@ResponseBody
		public Pagination editExecScriptFile(BidPubSettings bidPubSettings) {
			Pagination page = new Pagination(request);
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			try {
				BidPubSettings bidPubSettingsFromDb = (BidPubSettings) bidPubSettingsManager.getUniquerResult(BidPubSettings.class, "bidPubSettingsId", bidPubSettings.getBidPubSettingsId());
				if( bidPubSettingsFromDb!=null ){
					if(bidPubSettings.getScriptFile().equals(bidPubSettingsFromDb.getScriptFile()) && bidPubSettings.getScriptName().equals(bidPubSettingsFromDb.getScriptName()) ){
						page.setMsg("请勿重复提交！");
						page.setSuccess(false);
						return page;
					}
						bidPubSettingsFromDb.setScriptName(bidPubSettings.getScriptName());
						bidPubSettingsFromDb.setScriptSubmitUser(user.getId());
						Timestamp now =  DateUtil.getTimeStamp();
						bidPubSettingsFromDb.setScriptSubmitDatetime(now);
						bidPubSettingsFromDb.setUpdDatetime(now);
						bidPubSettingsFromDb.setUpdUser(user.getId());
						if(bidPubSettingsManager.update(bidPubSettingsFromDb)){
							BidPubSettingsLog bidPubSettingsLog = new BidPubSettingsLog();
							BeanCopierUtils.copyProperties(bidPubSettingsFromDb, bidPubSettingsLog);
							bidPubSettingsLog.setLogId(UUID.randomUUID().toString());
							bidPubSettingsManager.save(bidPubSettingsLog);
							page.setSuccess(true);
						}
					
				}else{
					page.setMsg("所选公示对象不存在！");
					page.setSuccess(false);
				}
			} catch (Exception e) {
				log.error("",e);
				page.setMsg("保存失败！请重新提交");
				page.setSuccess(false);
			}
			return page;
		}
		
		/**
		 * @category 执行sql语句 1.查出公示对象 2.根据公示脚本生成pdf文件 3.更新公示对象 4.保存日志
		 * @author 应晓川
		 * @date 2015年9月6日09:18:10
		 * @return
		 */
		@RequestMapping("/execScriptFile")
		@ResponseBody
		public Pagination execScriptFile(String bidPubSettingsId) {
			Pagination page = new Pagination(request);
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			try {
				BidPubSettings bidPubSettingsFromDb = (BidPubSettings) bidPubSettingsManager.getUniquerResult(BidPubSettings.class, "bidPubSettingsId", bidPubSettingsId);
				if(bidPubSettingsFromDb.getStatus()==1){
					page.setMsg("改公示已被执行，请勿重复操作！");
					page.setSuccess(false);
					return page;
				}
					page.getConditions().put("sql",bidPubSettingsFromDb.getScriptFile());
					page = bidPubSettingsManager.getExecScriptFileHashmapList(page);
					
					@SuppressWarnings("unchecked")
					List<HashMap<String,Object>> list  = (List<HashMap<String, Object>>) page.getRows();
					//根据sql生成pdf文件
					String rootPath = session.getServletContext().getRealPath("/");
					String file = PdfUtil.execSQLtoPdf(list,bidPubSettingsFromDb.getScriptName(),rootPath,filepath) ;
					if (StringUtils.isNotBlank(file)){
						bidPubSettingsFromDb.setPubFilepath(file);
						bidPubSettingsFromDb.setUpdUser(user.getId());
						Timestamp now =  DateUtil.getTimeStamp();
						bidPubSettingsFromDb.setUpdDatetime(now);
						bidPubSettingsFromDb.setExecUser(user.getId());
						bidPubSettingsFromDb.setExecDatetime(now);
						bidPubSettingsFromDb.setStatus(Constants.OP_TYPE_EDIT);
						if(bidPubSettingsManager.update(bidPubSettingsFromDb)){
							BidPubSettingsLog bidPubSettingsLog = new BidPubSettingsLog();
							BeanCopierUtils.copyProperties(bidPubSettingsFromDb, bidPubSettingsLog);
							bidPubSettingsLog.setLogId(UUID.randomUUID().toString());
							bidPubSettingsManager.save(bidPubSettingsLog);
							page.setSuccess(true);
						}
					}
			} catch (Exception e) {
				log.error("",e);
				page.setMsg("SQL执行失败！请重新输入");
				page.setSuccess(false);
			}
			return page;
		}
		/**
		 *@category 去查看项目公示结果
		 *@author 应晓川
		 *@date 2015年9月1日19:26:23
		 *@return
		 */
		@RequestMapping("/toResultList")
		public String toResultList(String projId){
			request.setAttribute("projId", projId);
			return "/pro/project/bidPubSettings/resultList";
		}
		
		/**
		 *@category 获取公示结果列表
		 *@author 应晓川
		 *@date 2015年9月1日19:26:23
		 *@return
		 */
		@RequestMapping("/getResultList")
		@ResponseBody
		public Pagination getResultList(String projId) {
			Pagination page = new Pagination(request);
			try {
				page.getConditions().put("projId", projId);
				page = bidPubSettingsManager.getBidPubSettingsResultList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
				page.setSuccess(false);
			}
			return page;
		}
		
		/**
		 *@category 去查看项目公示结果详情，即查看pdf文件
		 *@author 应晓川
		 *@date 2015年9月1日19:26:23
		 *@return
		 */
		@RequestMapping("/toDetailResult")
		public String toDetailResult(String bidPubSettingsId){
			BidPubSettings bidPubSettingsFromDb = (BidPubSettings) bidPubSettingsManager.getUniquerResult(BidPubSettings.class, "bidPubSettingsId", bidPubSettingsId);
			request.setAttribute("pubFilepath", bidPubSettingsFromDb.getPubFilepath());
			request.setAttribute("title", bidPubSettingsFromDb.getScriptName());
			// 根据公示表id调至到一个页面，显示pdf文件  
			return "/pro/project/bidPubSettings/detailResult";
		}
		
		/**
		 *@category 去公示查看
		 *@author 应晓川
		 *@date 2015年9月7日17:11:00
		 *@return
		 */
		@RequestMapping("/toListCheck")
		public String toListCheck(){
			List<Object> list = bidPubSettingsManager.getProjNameList();
			request.setAttribute("projNameList",list); 
			return "/pro/project/bidPubSettings/listCheck";
		}
		
		/**
		 * @category 获取已执行的公示列表
		 * @author 应晓川
		 * @date 2015年9月7日17:11:40
		 * @return
		 */
		@RequestMapping("/getListCheckByCenter")
		@ResponseBody
		public Pagination getListCheckByCenter(ProdProjectForm form) {
			Pagination page = new Pagination(request);
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			try {
				
				String defalutProjId=  user.getDefaultProjId();
				if (StringUtils.isNotBlank(defalutProjId)) {
					page.getConditions().put("defalutProjId", defalutProjId);
					form.setProjId(defalutProjId);
				}
				page.setForm(form);
				page = bidPubSettingsManager.getBidPubSettingsResultListCheck(page);
				page.setSuccess(true);
			} catch (Exception e) {
				log.error("",e);
				page.setSuccess(false);
			}
			return page;
		}
		
		/**
		 *@category 配送企业去公示查看
		 *@author 应晓川
		 *@date 2015年9月7日17:11:00
		 *@return
		 */
		@RequestMapping("/toListCheckByComp")
		public String toListCheckByComp(){
			List<Object> list = bidPubSettingsManager.getProjNameList();
			request.setAttribute("projNameList",list); 
			return "/pro/project/bidPubSettings/listCheckByComp";
		}
		
		/**
		 *@category 生产企业去公示查看
		 *@author 应晓川
		 *@date 2015年9月7日19:18:19
		 *@return
		 */
		@RequestMapping("/toListCheckByProdComp")
		public String toListCheckByProdComp(){
			List<Object> list = bidPubSettingsManager.getProjNameList();
			request.setAttribute("projNameList",list); 
			return "/pro/project/bidPubSettings/listCheckByProdComp";
		}
		
}
